import React from "react";
import { Button, Checkbox, Form, Input, message } from "antd";
import "./less/login.less";
import logo from "./logo.png";
import { UserOutlined, UnlockOutlined } from "@ant-design/icons";
import { Link, useNavigate } from "react-router-dom";
import { LoginApi } from "./request/api";
export default function Login() {
  const navigate = useNavigate();
  const onFinish = (values) => {
    console.log("Success:", values);
    LoginApi({
      username: values.username,
      password: values.password,
    }).then((res) => {
      if (res.errCode === 0) {
        message.success(res.message);

        localStorage.setItem("avatar", res.data.avatar);
        localStorage.setItem("cms-token", res.data["cms-token"]);
        localStorage.setItem("editable", res.data.editable);
        localStorage.setItem("player", res.data.player);

        localStorage.setItem("username", res.data.username);

        setTimeout(() => navigate("/"), 1000);
      } else {
        message.error(res.message);
      }
    });
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  return (
    <div className="login">
      <div className="login-box">
        <img src={logo} alt="" />
        <Form
          name="basic"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[
              {
                required: true,
                message: "Please input your username!",
              },
            ]}
          >
            <Input
              placeholder="请输入用户名"
              size="large"
              prefix={<UserOutlined />}
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              {
                required: true,
                message: "Please input your password!",
              },
            ]}
          >
            <Input.Password
              placeholder="请输入密码"
              size="large"
              prefix={<UnlockOutlined />}
            />
          </Form.Item>
          <Form.Item>
            <Link to="/register">还没用户？去注册</Link>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
